﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//using StockFinder.Services.Extractors.Google;
using StockFinder.Model;
using StockFinder.Model.Enumerations;
using StockFinder.Services.ChartPatterns;
using System.Diagnostics;
using System.Threading;
using StockFinder.Services.Extractors;
using StockFinder.Services.Extractors.Yahoo;

namespace Testharness
{
    public partial class FlatBaseFinderForm : Form
    {
        public FlatBaseFinderForm()
        {
            InitializeComponent();
        }

        private void _ClearResultsButton_Click(object sender, EventArgs e)
        {
            _ResultsDataGridView.DataSource = null;
        }

        private void _ClearSymbolsListButton_Click(object sender, EventArgs e)
        {
            _SymbolsListBox.Items.Clear();
        }

        private void _SymbolsListBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
                // allow them to continue
                // (without this, the cursor stays a "NO" symbol
                e.Effect = DragDropEffects.All;
        }

        private void _SymbolsListBox_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            if (files != null && files.Length > 0)
            {
                string filename = files[0];

                using (StreamReader sr = new StreamReader(filename))
                {
                    //make sure we havent reached the end
                    while (sr.Peek() >= 0)
                    {
                        //read the symbol line
                        string symbol = sr.ReadLine();

                        //does the list box contain the symbol
                        if (!_SymbolsListBox.Items.Contains(symbol))
                        {
                            try
                            {
                                _SymbolsListBox.Items.Add(symbol);
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.ToString());
                            }
                        }
                    }
                }

                //sort the symbols
                List<string> symbolsList = new List<string>();

                foreach (string symbol in _SymbolsListBox.Items)
                {
                    symbolsList.Add(symbol);
                }

                symbolsList.Sort();

                _SymbolsListBox.Items.Clear();

                foreach (string symbol in symbolsList)
                {
                    _SymbolsListBox.Items.Add(symbol);
                }

                _SymbolsCountLabel.Text = _SymbolsCountLabel.Text =
                    string.Format("{0} symbols", _SymbolsListBox.Items.Count);
            }
        }

        private void _SaveButton_Click(object sender, EventArgs e)
        {
            if (_SaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string location = _SaveFileDialog.FileName;

                StringBuilder stringBuilder = new StringBuilder();

                foreach (DataGridViewRow row in _ResultsDataGridView.Rows)
                {
                    //add the symbol name to the list
                    stringBuilder.AppendLine(row.Cells[0].Value.ToString());
                }

                //write out the file symbols
                File.WriteAllText(location, stringBuilder.ToString());
            }
        }

        private void _RunButton_Click(object sender, EventArgs e)
        {
            //Thread thread = new Thread(delegate()
            //    {
            //        int symbolsCount = 0;
            //        int symbolIndex = 0;

            //        #region Get symbols list

            //        List<Symbol> symbols = new List<Symbol>();

            //        //create the lsit of symbols
            //        foreach (string symbol in _SymbolsListBox.Items)
            //        {
            //            symbols.Add(new Symbol() { Name = symbol });
            //        }

            //        symbolsCount = symbols.Count;

            //        #endregion

            //        #region Get symbols exchange

            //        Debug.WriteLine("Getting exchanges...");

            //        SetProgressLabel("Getting exchanges...");

            //        IExchangeExtractor exchangeExtractor = new YahooExchangeExtractor();

            //        foreach (Symbol symbol in symbols)
            //        {
            //            //symbol.Exchange = exchangeExtractor.GetExchange(symbol);

            //            //Debug.WriteLine(string.Format("Symbol {0}. Exchange {1}",
            //            //    symbol.Name, symbol.Exchange));
            //        }

            //        #endregion

            //        #region Get prices from google

            //        System.Diagnostics.Debug.WriteLine("Getting prices from google");

            //        SetProgressLabel("Getting prices from google...");

            //        GoogleHistoricPriceExtractor priceExtractor = new GoogleHistoricPriceExtractor();
            //        HistoricPricesExtract result = null;                    

            //        //get latest prices foreach
            //        foreach (Symbol symbol in symbols)
            //        {
            //            Debug.WriteLine(string.Format("{0} {1}/{2}", symbol.Name, ++symbolIndex, symbolsCount));

            //            SetProgressBar(1, symbolsCount, symbolIndex);

            //            result = priceExtractor.GetHistoricPrices(symbol);

            //            //loaded prices ok?
            //            if (result.HistoricPricesExtractResult == HistoricPricesExtractResult.SUCCESS)
            //            {
            //                //yes so fill prices for symbol
            //                symbol.Prices = result.DailyPrices;

            //                Debug.WriteLine("Success");
            //            }
            //            else
            //            {
            //                Debug.WriteLine("Failed: " + result.Message);
            //            }
            //        }

            //        #endregion

            //        #region Generate the weekly prices for each

            //        Debug.WriteLine("Generating weekly prices");

            //        SetProgressLabel("Generating weekly prices...");

            //        symbols.ForEach(symbol => symbol.GenerateWeeklyPrices());

            //        #endregion

            //        #region Apply flat base pattern

            //        Debug.WriteLine("Applying flat base");

            //        SetProgressLabel("Appling flat base pattern...");

            //        IChartPattern flatBaseChartPattern = new WeeklyFlatBaseChartPattern();
            //        FlatBaseChartPatternResult patternResult = null;
            //        symbolIndex = 0;

            //        foreach (Symbol symbol in symbols)
            //        {
            //            Debug.WriteLine(string.Format("{0} {1}/{2}", symbol.Name, ++symbolIndex, symbolsCount));

            //            SetProgressBar(1, symbolsCount, symbolIndex);

            //            //try and apply the flat base chart pattern
            //            patternResult = flatBaseChartPattern.Apply(symbol) as FlatBaseChartPatternResult;

            //            if (patternResult.DoesFit)
            //            {
            //                //add the result to the grid
            //                AddResultGridViewRow(symbol.Name, patternResult);

            //                Debug.WriteLine("Success");
            //            }
            //            else
            //            {
            //                Debug.WriteLine("No fit");
            //            }
            //        }

            //        #endregion

            //        SetProgressLabel(string.Empty);
            //        SetProgressBar(0, 0, 0);
            //    });

            //thread.Name = "FlatBaseFinderThread";
            //thread.Start();
        }

        private void AddResultGridViewRow(string symbolName, FlatBaseChartPatternResult result)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate
                {
                    AddResultGridViewRow(symbolName, result);
                }));
            }
            else
            {
                _ResultsDataGridView.Rows.Add(symbolName, result.BaseLength, result.BaseHigh, 
                    result.BaseLow);
            }
        }

        private void SetProgressLabel(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate
                {
                    SetProgressLabel(message);
                }));
            }
            else
            {
                _ProgressLabel.Text = message;
            }
        }

        private void SetProgressBar(int minValue, int maxValue, int progress)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate
                {
                    SetProgressBar(minValue, maxValue, progress);
                }));
            }
            else
            {                
                _ProgressBar.Maximum = maxValue;
                _ProgressBar.Minimum = minValue;
                _ProgressBar.Value = progress;
            }
        }
    }
}
